<?php if ( ! defined('BASEPATH')) exit('This file does not run directly. Sorry.'); ?>
<?php
/**
 * Kalaisoo.
 *
 * A lightweight no-framework framework written in PHP.
 *
 * @package Kalaisoo
 * @author $Author: info@sah-company.com $
 * @version $Id: detach.php 134 2012-01-19 00:37:33Z info@sah-company.com $
 */

/**
 * Kalaisoo Detach Plugin Class.
 *
 * @package Kalaisoo
 * @subpackage Plugin
 * @author $Author: info@sah-company.com $
 */
class Detach_Plugin extends Plugin
{
	/**
	 * holds the input
	 *
	 * @var Input
	 */
	protected $input;

	/**
	 * constructs a new attach plugin.
	 */
	public function __construct()
	{
		parent::__construct();
		$this->init();
	}
	
	/**
	 * initializes the attach plugin.
	 */
	protected function init()
	{
		$this->registry->loader->lib(array('redbean'));
		$this->registry->loader->helper(array('url'));
		$this->input = new Input();
	}
	
	/**
	 * adds a new subform depending on type, id and path. The path is given as get parameter
	 *
	 * @param string $type
	 * @param mixed $id
	 */
	public function execute($type, $id)
	{
		$path = explode('/', $this->input->path);
		$tail = array_pop($path); // get rid of the last slash
		$id_to_detach = array_pop($path);
		$model_to_detach = array_pop($path);
		if ( ! $id_to_detach) return; // nothing to do in the database
		if (strpos($model_to_detach,'own')===0) {
			$model_to_detach = substr($model_to_detach, 3);
		} elseif (strpos($model_to_detach,'shared')===0) {
			$model_to_detach = substr($model_to_detach, 6);
		}
		$this->loadEnvironment($model_to_detach, $id_to_detach);
		// then trash it
		try {
			R::trash($this->record);
		} catch (Exception $e) {
			// uups, could not trash
		}
	}
	
	/**
	 * loads the beans model file and returns true.
	 *
	 * Load or dispense a bean of $type. When $id is not 0 (zero) then the bean will be
	 * loaded otherwise it will be dispensed.
	 * The bean is pushed to our view data.
	 *
	 * @param string $type
	 * @param mixed $id
	 * @return bool
	 */
	protected function loadEnvironment($type, $id = 0)
	{
		// load the model and its language file
		//$this->registry->loader->model($type, $load_language = true);
		// dispense or load a bean and give it to view
		if ( ! $id) {
			$this->record = R::dispense($type);
		} else {
			$this->record = R::load($type, $id);
		}
		return true;
	}
}